package com.hslxy.niukewang.controller;

import com.hslxy.niukewang.component.Page;
import com.hslxy.niukewang.entity.DiscussPost;
import com.hslxy.niukewang.entity.User;
import com.hslxy.niukewang.service.DiscussPostService;
import com.hslxy.niukewang.service.LikeService;
import com.hslxy.niukewang.service.UserService;
import com.hslxy.niukewang.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Controller
public class HomeController implements Constant {
    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @RequestMapping(path = "/", method = RequestMethod.GET)
    public String root(){
        return "forward:/index";
    }


    @RequestMapping(path = "/index", method = RequestMethod.GET)
    public String getIndexPage(Model model, Page page, @RequestParam(name = "orderMode", defaultValue = "0") int orderMode){
//        model会自动把page装进model
        page.setRows(discussPostService.findDiscussPostRows(0));
        page.setPath("/index?orderMode=" + orderMode);
        List<DiscussPost> discussPosts = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit(), orderMode);
        Optional.ofNullable(discussPosts).map((List<DiscussPost> posts) -> posts.stream().map(post -> {
                    Map<String, Object> stringObjectHashMap = new HashMap<>();
                    stringObjectHashMap.put("post", post);
                    User userById = userService.findUserById(post.getUserId());
                    stringObjectHashMap.put("user", userById);
                    Long entityLikeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                    stringObjectHashMap.put("likeCount", entityLikeCount);
                    return stringObjectHashMap;
                }
        ).collect(Collectors.toList())).ifPresent(maps1 -> model.addAttribute("discussPosts", maps1));
        model.addAttribute("orderMode", orderMode);
        return "/index";
    }

    @RequestMapping(path = "/error", method = RequestMethod.GET)
    public String getErrorPage(Model model, Page page){
        return "/error/500";
    }

    @RequestMapping(path = "/denied", method = {RequestMethod.GET})
    public String getDeniedPage() {
        return "/error/404";
    }

}
